import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
  RouteRecordRaw,
} from "vue-router";
import HomeView from "../views/HomeView.vue";
import { getToken } from "@/utils/localStorage";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/",
    name: "home",
    meta: { isAuth: true, title: "消息" },
    component: HomeView,
    // redirect: "/list",
    /*  redirect(to) {
      console.log(to);
      return { path: "/message" };
    }, */
    children: [
      {
        path: "/home",
        redirect: "/list",
      },
      {
        path: "/list",
        name: "list",
        component: () => import("../views/ListView.vue"),
      },
      {
        path: "/about",
        name: "about",
        component: () => import("../views/AboutView.vue"),
      },
      {
        path: "/message",
        name: "message",
        component: () => import("../views/MessageView.vue"),
      },
      {
        path: "/mine",
        name: "mine",
        component: () => import("../views/MineView.vue"),
      },
      {
        path: "/virtual",
        name: "virtual",
        component: () => import("../views/VirtualList.vue"),
      },
      {
        path: "/css",
        name: "css",
        component: () => import("../views/CssView.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginView.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("../views/NotFound.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    redirect: "/404",
  },
];

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL),
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  // console.log("前置路由守卫", to, from);

  if (!getToken() && to.path !== "/login") {
    //判断是否需要鉴权
    next("/login");
  } else {
    next();
  }
});

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
// router.afterEach((to, from) => {
//   console.log("后置路由守卫", to, from);
// });

export default router;
